package com.zhixue.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixue.content.config.MultipartSupportConfig;
import com.zhixue.content.feignclient.MediaServiceClient;
import com.zhixue.content.mapper.*;
import com.zhixue.content.model.dto.*;
import com.zhixue.content.model.po.*;
import com.zhixue.content.service.*;
import com.zhixue.exception.ZhixuePlusException;
import com.zhixue.message.model.po.MqMessage;
import com.zhixue.message.service.MqMessageService;
import freemarker.template.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * @Auther: 李 力
 * @Date: 2025/5/3
 * @Description: com.zhixue.content.service.impl
 * @version: 1.0
 */
@Slf4j
@Service
public class CoursePublishServiceImpl extends ServiceImpl<CoursePublishMapper, CoursePublish> implements CoursePublishService {

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Autowired
    private CourseTeacherMapper teacherMapper;

    @Autowired
    private CoursePublishPreMapper publishPreMapper;

    @Autowired
    private CoursePublishMapper publishMapper;

    @Autowired
    private MqMessageService mqMessageService;

    @Autowired
    private MediaServiceClient mediaServiceClient;

    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        if (courseId == null) {
            throw new ZhixuePlusException("参数为null");
        }
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        CourseBaseInfoDto courseBaseInfoDto = courseBaseService.getInfoById(courseId);
        List<TeachplanDto> teachplanInfo = teachplanService.getTeachplanInfo(courseId);
        coursePreviewDto.setCourseBase(courseBaseInfoDto);
        coursePreviewDto.setTeachplans(teachplanInfo);
        return coursePreviewDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commitAudit(Long companyId, Long courseId) {
        if (companyId == null || courseId == null) {
            throw new ZhixuePlusException("参数为null");
        }
        //查询课程基本信息，营销信息，计划等信息
        CourseBaseInfoDto courseBaseInfoDto = courseBaseService.getInfoById(courseId);
        if (courseBaseInfoDto == null) {
            throw new ZhixuePlusException("课程找不到");
        }
        // todo 本机构只能提交本机构的课程

        //判断审核状态
        String auditStatus = courseBaseInfoDto.getAuditStatus();
        if ("202003".equals(auditStatus)) {
            throw new ZhixuePlusException("课程已提交，请等待审核");
        }
        //课程图片信息，计划信息校验
        String pic = courseBaseInfoDto.getPic();
        if (StringUtils.isEmpty(pic)) {
            throw new ZhixuePlusException("请上传课程图片");
        }
        List<TeachplanDto> teachplanInfo = teachplanService.getTeachplanInfo(courseId);
        if (teachplanInfo == null || teachplanInfo.isEmpty()) {
            throw new ZhixuePlusException("请编写课程计划");
        }

        //课程预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfoDto, coursePublishPre);
        coursePublishPre.setCompanyId(companyId);
        //营销信息
        CourseTeacher courseTeacher = courseTeacherMapper.selectById(courseId);
        String market = JSON.toJSONString(courseTeacher);
        coursePublishPre.setMarket(market);
        //计划信息
        String plan = JSON.toJSONString(teachplanInfo);
        coursePublishPre.setTeachplan(plan);
        //教师信息
        LambdaQueryWrapper<CourseTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseTeacher::getCourseId, courseId);
        List<CourseTeacher> courseTeachers = teacherMapper.selectList(wrapper);
        String teachers = JSON.toJSONString(courseTeachers);
        coursePublishPre.setTeachers(teachers);
        //状态
        coursePublishPre.setStatus("202003");
        CoursePublishPre publishPre = publishPreMapper.selectById(courseId);
        if (publishPre == null) {
            publishPreMapper.insert(coursePublishPre);
        } else {
            publishPreMapper.updateById(coursePublishPre);
        }
        //更新课程基本信息表
        CourseBase courseBase = courseBaseService.getById(courseId);
        courseBase.setAuditStatus("202003");
        courseBaseService.updateById(courseBase);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publish(Long companyId, Long courseId) {
        //参数校验
        if (companyId == null || courseId == null) {
            throw new ZhixuePlusException("参数为null");
        }
        //todo 机构校验
        //查询预发布表
        CoursePublishPre coursePublishPre = publishPreMapper.selectById(courseId);
        if (coursePublishPre == null) {
            throw new ZhixuePlusException("无对应的课程");
        }
        //审核状态校验
        String status = coursePublishPre.getStatus();
        if (!"202004".equals(status)) {
            throw new ZhixuePlusException("课程未审核通过");
        }
        //向发布表写数据
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        CoursePublish coursePublishObj = publishMapper.selectById(courseId);
        if (coursePublishObj == null) {
            publishMapper.insert(coursePublish);
        } else {
            publishMapper.updateById(coursePublish);
        }
        //todo 向消息表写记录
        addMessage(courseId);

        //删除预发布表的数据
        publishPreMapper.deleteById(courseId);
    }

    @Override
    public File generateCourseHtml(Long courseId) {
        //静态化文件
        File htmlFile = null;
        try {
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");
            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");
            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);
            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course", ".html");
            log.debug("课程静态化，生成静态文件:{}", htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("课程静态化异常:{}", e.toString());
            throw new ZhixuePlusException("课程静态化异常");
        }
        return htmlFile;
    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String course = mediaServiceClient.upload(multipartFile, "course/" + courseId + ".html");
        if (course == null) {
            throw new ZhixuePlusException("上传课程页面到minio失败");
        }
    }

    private void addMessage(Long courseId) {
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", courseId.toString(), null, null);
        if (mqMessage == null) {
            throw new ZhixuePlusException("新增消息失败");
        }
    }

    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        if (courseId == null) {
            throw new ZhixuePlusException("参数为空");
        }
        return publishMapper.selectById(courseId);
    }
}
